import passport from 'passport'
import { Strategy as GoogleStrategy } from 'passport-google-oauth20'
import { User } from './../models/user.js'
import jwt from 'jsonwebtoken'
import { connectToDatabase } from './../db/mongo'

import { fromNodeMiddleware } from 'h3'

export default fromNodeMiddleware((req, res, next) => {
    passport.use(new GoogleStrategy({
        clientID: useRuntimeConfig().public.googleClientId,
        clientSecret: process.env.GOOGLE_CLIENT_SECRET,
        callbackURL: `${useRuntimeConfig().public.siteUrl}/api/auth/google/callback`
    },
        async (accessToken, refreshToken, profile, done) => {
            await connectToDatabase()
            try {
                const existingUser = await User.findOne({ googleId: profile.id })

                if (existingUser) {
                    return done(null, existingUser)
                }

                const newUser = new User({
                    email: profile.emails[0].value,
                    googleId: profile.id,
                    emailVerified: true
                })

                await newUser.save()
                done(null, newUser)
            } catch (error) {
                done(error)
            }
        }))

    passport.serializeUser((user, done) => done(null, user._id))
    passport.deserializeUser(async (id, done) => {
        try {
            const user = await User.findById(id)
            done(null, user)
        } catch (error) {
            done(error)
        }
    })
    
    // 初始化Passport中间件
    passport.initialize()(req, res, next)
})